package com.xq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xq.base.IBaseMapper;
import com.xq.entity.CityInfo;
import com.xq.entity.UserInfo;
import com.xq.exception.BizException;
import com.xq.mapper.CityInfoMapper;
import com.xq.mapper.UserInfoMapper;
import com.xq.service.IdentityService;
import com.xq.service.UserService;
import com.xq.vo.IdentityVo;
import com.xq.vo.JsonRootBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Log4j2
@Service
public class UserInfoServiceImpl implements UserService {

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(32,52,1L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200));

   @Autowired
   private ApplicationContext applicationContext;

    @Autowired
    private CityInfoMapper cityInfoMapper;

    @Autowired
    public UserInfoMapper userInfoMapper;

    @Autowired
    public IdentityService identityService;

    @Autowired
    UserService userService;

    public UserInfo getUser(String mobile){
        UserInfo userInfo = new UserInfo();
        userInfo.setMobile(mobile);
        return userInfoMapper.selectOne(userInfo);
    }

    public void identity(IdentityVo identityVo) throws Exception{
        //身份证正面对比
        CompletableFuture<Boolean> f1 =  CompletableFuture.supplyAsync(()->{
            boolean flag = false;
            try {
                String base64 = Base64.getEncoder().encodeToString(identityVo.getFrontImage().getBytes());
                String str = identityService.identityAuth(identityVo.getName(), identityVo.getCardId(), base64);
                JSONObject json = JSON.parseObject(str);
                Integer code = json.getInteger("code");
                //0代表成功
                if(code==0){
                    JSONObject data = json.getJSONObject("data");
                    Integer score = data.getInteger("score");
                    if(score>50){
                        flag=true;
                    }
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return flag;
        },threadPoolExecutor);


        //活体照片对比
        CompletableFuture<Boolean> f2 = CompletableFuture.supplyAsync(()->{
            boolean flag = false;
            try {
                String base64 = Base64.getEncoder().encodeToString(identityVo.getLiveImage().getBytes());
                String str = identityService.liveAuth(base64);
                JSONObject json = JSON.parseObject(str);
                Integer code = json.getInteger("code");
                //0代表成功
                if(code==0){
                    JSONObject data = json.getJSONObject("data");
                    Integer score = data.getInteger("score");
                    if(score>50){
                        flag=true;
                    }
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return flag;
        },threadPoolExecutor);

        //3张照片上传
        CompletableFuture<Map<String, String>> f3 = CompletableFuture.supplyAsync(()->{
            //存上传成功后的路径
            Map<String, String> map = new HashMap<>();
            try {
                //上传到文件服务器
                Thread.sleep(1000);
                //正面
                map.put("frontImageUrl", "http://127.0.0.1:8081/" + UUID.randomUUID() + ".jpg");
                //反面
                map.put("backImageUrl", "http://127.0.0.1:8081/" + UUID.randomUUID() + ".jpg");
                //活体照片
                map.put("liveImageUrl", "http://127.0.0.1:8081/" + UUID.randomUUID() + ".jpg");
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return map;
        },threadPoolExecutor);

        CompletableFuture.allOf(f1,f2,f3).join();
        Boolean identityFlag = f1.get();
        Boolean lieveFlag = f2.get();
        Map<String,String> map = f3.get();
        if(identityFlag && lieveFlag && MapUtil.isNotEmpty(map)){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(1L);
            userInfo.setUserName(identityVo.getName());
            userInfo.setUserCardId(identityVo.getCardId());
            userInfo.setLinkFront(map.get("frontImageUrl"));
            userInfo.setLinkBack(map.get("backImageUrl"));
            userInfo.setLinkHand(map.get("liveImageUrl"));
            userInfoMapper.updateByPrimaryKey(userInfo);
        }else {
            throw new BizException(400,"身份认证失败");
        }
    }

   //@Transactional(rollbackFor = Exception.class)
   public void a(){

         //存储引擎如果是Myisam
         //如果抛出的异常是非RuntimeException
       //带有事务的方法不能是private

       //插入订单
       //插入订单明细
         //
       //
       UserInfoServiceImpl userService = applicationContext.getBean(UserInfoServiceImpl.class);
       userService.b();
       //userService.c();

       //b();
       //c();


   }


    @Transactional(rollbackFor = Exception.class)
    public void b(){
        //插入订单

    }

    @Transactional(rollbackFor = Exception.class)
    public void c(){
        //插入订单明细
    }

    //@PostConstruct
    @Transactional(rollbackFor = Exception.class)
    public void init(){
        String str = HttpUtil.get("https://mxnzp.com/api/address/list?app_id=pnjgrriit6wghnlo&app_secret=YXBoenBlWnZmanhLWTRxenNCL1p3Zz09");
        System.out.println(str);
        if(StringUtils.isBlank(str)){
            return;
        }
        JsonRootBean json = JSON.parseObject(str,JsonRootBean.class);
        if(json.getCode()!=1){
            log.info("访问失败:"+json.getMsg());
            return;
        }
        if(CollectionUtils.isEmpty(json.getData())){
            log.info("数据为空:");
            return;
        }

        json.getData().forEach(c->{
            CityInfo cityInfo = new CityInfo();
            cityInfo.setCode(c.getCode());
            cityInfo.setName(c.getName());
            cityInfo.setPid(0L);
            cityInfo.setSub(1);
            cityInfo.setpCode("0");
            cityInfoMapper.insertUseGeneratedKeys(cityInfo);
            if(CollectionUtil.isNotEmpty( c.getPchilds())){
                c.getPchilds().forEach(p->{
                    CityInfo cityInfo2 = new CityInfo();
                    cityInfo2.setCode(p.getCode());
                    cityInfo2.setName(p.getName());
                    cityInfo2.setSub(2);
                    cityInfo2.setpCode(c.getCode());
                    cityInfo2.setPid(cityInfo.getId());
                    cityInfoMapper.insertUseGeneratedKeys(cityInfo2);

                    p.getCchilds().forEach(cchilds -> {
                        CityInfo cityInfo3 = new CityInfo();
                        cityInfo3.setCode(cchilds.getCode());
                        cityInfo3.setName(cchilds.getName());
                        cityInfo3.setSub(3);
                        cityInfo3.setpCode(p.getCode());
                        cityInfo3.setPid(cityInfo2.getId());
                        cityInfoMapper.insertUseGeneratedKeys(cityInfo3);
                    });

                });
            }


        });
    }



    public String sendSms(String mobile, String content){
       Map<String,Object> map = new HashMap<String,Object>();
        map.put("uid","用户id从配置文件读取");
        map.put("pw","密码明文从配置文件读取");
        map.put("mb",mobile);//用户手机号，多个用,分割
        map.put("ms",content);//短信内容
        String result = HttpUtil.post("http://服务器 ip:18002/send.do",map,5000);
        System.out.println(result);
        return null;
    }




    public String sendSmsList(List mobileList, String content){
        String mobilesStr = StringUtils.join(mobileList,",");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("uid","用户id从配置文件读取");
        map.put("pw","密码明文从配置文件读取");
        map.put("mb",mobilesStr);//用户手机号，多个用,分割
        map.put("ms",content);//短信内容
        String result = HttpUtil.post("http://服务器 ip:18002/send.do",map,5000);
        return null;
    }


}